//
//  RMMChongZhiViewController.m
//  Romomo
//
//  Created by puman on 16/10/17.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMChongZhiViewController.h"
#import "RMMChongZhiView.h"

@interface RMMChongZhiViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMChongZhiViewController
{
    UITableView *_tableView;
    RMMChongZhiView *_chongZhiView;
    RMMPayFailureView *_failureView;
    RMMPayResultView *_resultView;
    NSMutableArray *_dataArray;
    UIView *_backView;
    NSArray *_imageNameArr;
    NSArray *_titleArr;
    NSString *_money;
    NSString *_pay_way_code;
    BOOL _isSuccess;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"充值中心";
    self.view.backgroundColor = kWhiteColor;
    [self addViews];
    [self getChongZhiData];
    // Do any additional setup after loading the view.
}
- (void)addViews{
    [self addLeftItem];
    _isSuccess = YES;
    _chongZhiView = [[RMMChongZhiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    BUTTON_S(_chongZhiView.chongZhiBut, chongZhiButClick);
    _chongZhiView.label.text = [NSString stringWithFormat:@"¥%@",_balance];
    [self.view addSubview:_chongZhiView];
    for (int i = 0; i < 6; i++) {
        UIButton *button = [self.view viewWithTag:10 + i];
        BUTTON_S(button, moneyButClick:);
    }
    [self addPayTypeBackView];
}
- (void)getChongZhiData{
    NSString *url = GetChongZhiMoneyUrl;
    [OSRequestManager requestWithUrlString:url parDic:nil method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [_dataArray removeAllObjects];
            NSDictionary *dic = dataDic[@"data"];
            [_dataArray addObject:dic[@"LVL1"]];
            [_dataArray addObject:dic[@"LVL2"]];
            [_dataArray addObject:dic[@"LVL3"]];
            [_dataArray addObject:dic[@"LVL4"]];
            [_dataArray addObject:dic[@"LVL5"]];
            [_dataArray addObject:dic[@"LVL6"]];
            _chongZhiView.dataArray = _dataArray;
        } else {
            _chongZhiView.dataArray = _dataArray;
        }
    } error:^(NSError *errors) {
        _chongZhiView.dataArray = _dataArray;
        
    } view:self.view];
}
- (void)addPayTypeBackView{
    _dataArray = [NSMutableArray arrayWithArray:@[@"1000",@"2000",@"2500",@"3000",@"5000",@"10000"]];
    _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    [self.view addSubview:_backView];
    
    UIButton *button =[UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(0, 0, kScreenWideth, _backView.height - 80 -_titleArr.count * 80);
    BUTTON_S(button, cancelClick);
    [_backView addSubview:button];
    
    _imageNameArr = @[@"微信支付@3x",@"支付宝@3x"];
    _titleArr = @[@"微信支付",@"支付宝支付"];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _backView.bottom, kScreenWideth, 80 + _titleArr.count * 80) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    [_backView addSubview:_tableView];
    _backView.hidden = YES;
    _backView.alpha = 0.0;
    
    _failureView = [[RMMPayFailureView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    BUTTON_S(_failureView.backHomeBut, backHomeButClick:);
    BUTTON_S(_failureView.goonPayBut, backHomeButClick:);
    _failureView.hidden = YES;
    [self.view addSubview:_failureView];
    
    _resultView = [[RMMPayResultView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _resultView.hidden = YES;
    BUTTON_S(_resultView.doneBut, doneButClick);
    [self.view addSubview:_resultView];

    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _titleArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 30)];
    view.backgroundColor = kWhiteColor;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenWideth - 30, view.height)];
    label.text = @"选择支付方式";
    label.font = kFont(13);
    label.textColor = COLORFROMCODE(0x4A4A4A, 1);
    [view addSubview:label];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kHalf)];
    view.backgroundColor = RGBA(243, 242, 243, 1);
    UIButton *button =[UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(0, 5, kScreenWideth, 45);
    button.backgroundColor = kWhiteColor;
    [button setTitle:@"取消" forState:(UIControlStateNormal)];
    button.titleLabel.font = kFont(16);
    BUTTON_S(button, cancelClick);
    [button setTitleColor:COLORFROMCODE(0x4A4A4A, 1) forState:(UIControlStateNormal)];
    [view addSubview:button];
    return view;

}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return kHalf;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell.imageView.image = [UIImage imageNamed:_imageNameArr[indexPath.row]];
    cell.textLabel.text = _titleArr[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"%ld",indexPath.row);
    _pay_way_code = @"";
    if (indexPath.row == 0) {
        // 微信支付
        _pay_way_code = @"7";
    } else if (indexPath.row == 1) {
        // 支付宝支付
        _pay_way_code = @"8";
    } 
    [self cancelClick];
    [self getOder];
}
// 支付
- (void)getOder{
    [RMMFileManager shareHandle].payTypeName = @"会员卡充值";
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    parDic[@"cust_id"] = cust_id;
    parDic[@"org_no"] = Org_no;
    parDic[@"rechargeAtm"] = _money;
    parDic[@"pay_way_code"] = _pay_way_code;
    parDic[@"order_source"] = @"1";
    NSString *url = GetRechargeVIPUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self aliPayWithOrder_no:dataDic[@"data"]];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];
}
// 支付宝支付
- (void)aliPayWithOrder_no:(NSString *)order_no{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"order_no"] = order_no;
    parDic[@"atm"] = _money;
    NSString *url = @"";
    if ([_pay_way_code isEqualToString:@"5"]) {
        [self paySuccess];
        return;
    } else if ([_pay_way_code isEqualToString:@"7"]) {
        // 微信支付
        url = WeChatPayUrl;
    } else if ([_pay_way_code isEqualToString:@"8"]) {
        // 支付宝支付
        url = GetALiPaySignUrl;
    } else {
        
    }
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NS_ADD(payJieGuo:, @"PAYJIEGUOFUWU", @"会员卡充值");
            if ([_pay_way_code isEqualToString:@"5"]) {
                // 会员卡
            } else if ([_pay_way_code isEqualToString:@"7"]) {
                // 微信
                [self wechatPayWith:dataDic];
            } else if ([_pay_way_code isEqualToString:@"8"]) {
                // 支付宝
                [self aLipayWith:[RMMPayManager backSingWithDic:dataDic[@"data"]]];
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {         
    } view:self.view];
}
// 微信支付
- (void)wechatPayWith:(NSDictionary *)dataDic{
    NSDictionary *dic = dataDic[@"data"];
    PayReq *request = [[PayReq alloc] init];
    request.partnerId                 = dic[@"partnerid"];
    request.prepayId                  = dic[@"prepayid"];
    request.package                   = dic[@"package"];
    request.nonceStr                  = dic[@"noncestr"];
    request.sign                      = dic[@"sign"];
    request.timeStamp                 = [dic[@"timestamp"] doubleValue];
    [WXApi sendReq:request];
}
// 支付宝
- (void)aLipayWith:(NSString *)sign{
    [[AlipaySDK defaultService] payOrder:sign fromScheme:ALiPaySchemes callback:^(NSDictionary *resultDic) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
        NSLog(@"reslut = %@",resultDic);
    }];
}
- (void)payJieGuo:(NSNotification *)notification{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
    if([notification.object isEqualToString:@"会员卡充值"]){
        NSDictionary *dic = [notification userInfo];
        if ([_pay_way_code isEqualToString:@"5"]) {
            // 会员卡
        } else if ([_pay_way_code isEqualToString:@"7"]) {
            // 微信
            NSString *type = dic[@"type"];
            if ([type isEqualToString:@"成功"]) {
                [self paySuccess];
            } else {
                [self payFailure];
                _failureView.titleName = @"失败";
            }
        } else if ([_pay_way_code isEqualToString:@"8"]) {
            // 支付宝
            NSString *status = dic[@"resultStatus"];
            if ([status isEqualToString:@"9000"]) {
                // 支付成功
                [self paySuccess];
            } else {
                [self payFailure];
                _failureView.titleName = dic[@"memo"];
            }
        }
    }
}
// 支付成功
- (void)paySuccess{
    // 支付成功
    if (_isSuccess) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
        _isSuccess = NO;
        _resultView.hidden = NO;
        _resultView.titelName = @"购买服务";
        _resultView.price = _money;
        _failureView.hidden = YES;
        self.navigationItem.title = @"支付结果";
        [RMMFileManager shareHandle].thred = @"1";
        NS_POST(@"ORDERUPDATA", nil, nil);
        NS_POST(@"SHOPFRESH", nil, nil);
        NS_POST(@"UPDATEMINEDATA", nil, nil);
    }
}
- (void)payFailure{
    // 支付失败
    // [RMMFileManager MBProgressWith:dic[@"memo"] onView:self.view];
    _resultView.hidden = YES;
    _failureView.hidden = NO;
    self.navigationItem.title = @"支付结果";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
}
- (void)doneButClick{
    _memBlock();
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)backHomeButClick:(UIButton *)button{
    if (button == _failureView.backHomeBut) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self getOder];
    }
}
- (void)moneyButClick:(UIButton *)button{
    _money = [[button titleForState:(UIControlStateNormal)] substringFromIndex:1];
    for (int i = 0; i < 6; i++) {
        UIButton *buttons = [self.view viewWithTag:10 + i];
        buttons.backgroundColor = kWhiteColor;
        [buttons setTitleColor:kBasicColor forState:(UIControlStateNormal)];
        if (button.tag == buttons.tag) {
            buttons.backgroundColor = kBasicColor;
            [buttons setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
        }
    }
    [_chongZhiView.chongZhiBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    _chongZhiView.chongZhiBut.backgroundColor = kBasicColor;
    _chongZhiView.chongZhiBut.userInteractionEnabled = YES;
}
- (void)addLeftItem{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = item;
   // item.tintColor = COLORFROMCODE(0x9B9B9B1, 1);
    
}
- (void)cancelClick{
    [UIView animateWithDuration:kInterval animations:^{
        _backView.alpha = 0.0;
        _tableView.frame = CGRectMake(0,  _backView.bottom, kScreenWideth, 80 + _titleArr.count * 80);
    } completion:^(BOOL finished) {
        _backView.hidden = YES;
    }];
}
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)chongZhiButClick{
    _backView.hidden = NO;
    [UIView animateWithDuration:kInterval animations:^{
        _backView.alpha = 1.0;
        _tableView.frame = CGRectMake(0,  _backView.height - 80 -_titleArr.count * 80, kScreenWideth, 80 + _titleArr.count * 80);
    } completion:^(BOOL finished) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
